import org.grails.taggable.Taggable
class Entry implements Comparable, Taggable {
  static mapping = {
    table 'yuying_entry'
    content type:"text"    
  }
  String title
  String content
  String description
  String tagNames
  String contentType
  String source
  String sourceUrl
  Person creator
  Long hits
  Integer recommend
  Integer stage
  String depth
  Date dateCreated
  Date lastUpdated
  Catalog catalog
  Long rootCatalogId

  static constraints = {
    title()
    content()
    catalog(nullable: true)
    description(nullable: true)
    tagNames(nullable: true)
    contentType(nullable: true)
    source(nullable: true)
    sourceUrl(nullable: true)
    creator(nullable: true)
    hits(nullable: true)
    recommend(nullable: true)
    stage(nullable: true)
    depth(nullable: true)
    rootCatalogId(nullable: true)
  }

  def beforeInsert = {
     if(catalog){
       depth = catalog.depth
       rootCatalogId = getRootCatalog().id
     }
  }

  def getRootCatalog(){
    if(!catalog) return null
    def cat = catalog
    def c = 0
    while(cat.parent){
      cat = cat.parent
      if(c++ > 20) break;
    }
    return cat
  }
  
  def beforeUpdate = {
    if(catalog){
      depth = catalog.depth
      rootCatalogId = getRootCatalog().id
    }    
  }

  public int compareTo(Object o) {
    if(stage != o.stage){
      return stage.compareTo(o.stage)
    } else {
      return dateCreated.compareTo(o.dateCreated)
    }
  }
}
